<template>
  <div class="my-report-handle">
    <template>
      <header-bar :title="btnShow?'事件处理':'违停登录'" v-show="barShow">
        <template v-slot:backBtn>
          <i @click="$emit('handleChange')" class="iconarrow_back"></i>
        </template>
      </header-bar>
      <div class="handle-content" :class="{fullHeight: !barShow}">
        <cube-scroll>
          <!-- 默认填写项 -->
          <div class="border-line flex-line bg-white" v-show="btnShow">
            <span class="name-space">处理方式<i class="require"></i></span>
            <picker-common
              :selectData.sync="handleType"
              :pickerList="dealWay"
              :title="'处理方式'"
              :alias="{ value: 'id', text: 'name' }"
              :selectVal="handleType"
            ></picker-common>
          </div>
          <div v-if="selectHandle == 0 || selectHandle == 5">
            <persuaded ref="persuaded" :handleType="selectHandle"></persuaded>
          </div>
          <div v-if="selectHandle == 2">
            <no-found ref="noFound"></no-found>
          </div>
          <div v-if="selectHandle == 4">
            <illegal-park ref="illegalPark" @hideMain="hideMain" @back="$emit('handleChange')"></illegal-park>
          </div>
        </cube-scroll>
      </div>
      <div class="btn-group" v-show="btnShow">
        <div @click="clickSubmit" class="deal-btn">
          提 交
        </div>
      </div>
    </template>
  </div>
</template>

<script>
/**
 * 我的任务事件处理处理页面
 */
import { valiData } from "@/common/js/utils";
import { uploadFiles } from "@/api/upload.js";
import { noFoundApi, advised, correction, judgeHandle } from "@/api/eventAPI.js";
export default {
  components: {
    "header-bar": () => import("@/components/header-bar/header-bar"),
    "picker-common": () => import("@/components/picker-common/picker-common"),
    "no-found": () => import("@/views/task-info/handleType/noFound.vue"),
    "persuaded": () => import("@/views/task-info/handleType/persuaded.vue"),
    "illegal-park": () => import("@/views/task-info/handleType/illegalPark.vue")
  },
  props: {
    baseData: {
      type: Object,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      communicateType: { id: "", text: "" },
      handleType: { id: 0, text: "教育劝改" },
      cardType: { id: "1", text: "身份证" },
      selectHandle: 0,
      dealWay: [
        // 处理方式
        { id: 0, name: "教育劝改" },
        { id: 2, name: "无发现" },
        // { id: 4, name: "违停处理" },
        { id: 5, name: "责令改正" }
      ],
      communication: [
        {
          value: 1,
          text: "电话沟通"
        },
        {
          value: 2,
          text: "短信沟通"
        },
        {
          value: 3,
          text: "当面沟通"
        }
      ],
      cardList: [
        {
          value: "1",
          text: "身份证"
        },
        {
          value: "2",
          text: "台胞证"
        },
        {
          value: "3",
          text: "港澳身份证"
        }
      ],
      submitData: {
        //  提交数据
        communicateType: null,
        remark: "",
        cardType: "1",
        litigantName: "",
        litigantId: "",
        litigantType: 1,
        litigantCode: "",
        creditCode: "",
        litigantLegal: "",
        eventId: "",
        personEnclosureUrl: "",
        processingDocument: "",
        processingAudio: ""
      },
      uploadImgs: [],
      // 选择当事人
      options: ["个人", "单位"],
      selectedLitigantType: "个人",
      // 无发现
      description: "",
      param: {}, //用来保存请求json
      toast: null, // mask
      // 责令改正部分
      uploadDoc: [],
      uploadAudio: [],
      selectedDoc: "上传图片",
      options2: ["上传图片", "绑定文书"],
      number: 1,
      inputLength: 1,
      btnShow: true, // 隐藏头部和按钮
      barShow: true
    };
  },
  computed: {
    eventNode() {
      return this.$route.query.eventNode;
    },
    path() {
      return this.$route.path;
    },
    userInfo() {
      return JSON.parse(window.localStorage.getItem("user"));
    }
  },
  watch: {
    handleType(n) {
      this.selectHandle = n.id;
    }
  },
  mounted() {},
  methods: {
    showToast(msg) {
      this.$createToast({
        txt: msg,
        type: "error"
      }).show();
    },
    _canconfirm() {
      return this.$refs.upload.files.every(item => {
        return item.status === "success";
      });
    },
    async clickSubmit() {
      let orgLevel = this.$route.query.orgLevel
      let eventId = this.$route.query.id
      if(eventId && orgLevel) {
        let userId = orgLevel == 4 ? this.userInfo.userId : this.userInfo.groupId
        let judge = await judgeHandle(eventId, userId, orgLevel);
        if(judge.code !== 0) {
          this.$createToast({
            txt: '该条事件已被处理',
            type: 'error'
          }).show()
          return
        }
      }

      this.toast = this.$createToast({
        time: 0,
        mask: true,
        txt: "正在整合上传文件...."
      });
      this.toast.show();
      // form验证
      try {
        // 劝改或改正
        if (this.selectHandle === 0 || this.selectHandle === 5) {
          let submitData = this.$refs.persuaded.submitData
          this.param = {
            assigner: eventId ? this.$route.query.orgLevel : this.userInfo.orgLevel,
            communicateType: submitData.communicateType,
            remark: submitData.remark, //  沟通方式id
            eventId: this.$route.query.id,
            cardType: submitData.cardType,
            litigantName: submitData.litigantName,
            // litigantId: this.submitData.litigantType,
            litigantType: submitData.litigantType,
            litigantCode: submitData.litigantCode,
            creditCode: submitData.creditCode,
            userId: this.userInfo.userId,
            userName: this.userInfo.userName,
            userOrgId: this.userInfo.groupId,
            userOrgName: this.userInfo.groupName
          };
          const res = await uploadFiles(this.$refs.persuaded.uploadImgs); // 上传文件到 OSS
          this.param.personEnclosureUrl = JSON.stringify([...res]);
          // 责令改正
          if (this.selectHandle === 5) {
            if (this.$refs.persuaded.selectedDoc == "上传图片") {
              const res = await uploadFiles(this.$refs.persuaded.uploadDoc); // 上传文件到 OSS
              this.param.processingDocument = JSON.stringify([...res]);
            } else {
              let input = document.querySelectorAll(".bind-doc .cube-input");
              for (let i of input) {
                if (!i.children[0].value) {
                  this.$createToast({
                    txt: "您还有未填写的文书号",
                    type: "error"
                  }).show();
                  return false;
                }
              }
              this.param.processingDocument = this.$refs.persuaded.getBindDoc();
            }
            const res = await uploadFiles(this.$refs.persuaded.uploadAudio); // 上传文件到 OSS
            console.log(res);
            
            this.param.processingAudio = JSON.stringify([...res]);
          }

          if (
            !valiData.call(
              this,
              {
                communicateType: {
                  cond: "/\\d+/.test($$)",
                  pro: "请选择沟通方式"
                },
                remark: {
                  cond: "String($$).trim().length>0",
                  pro: "请输入处理意见"
                },
                personEnclosureUrl: {
                  cond: "String($$).trim().length>3",
                  pro: "请选择事件图片"
                }
              },
              this.param
            )
          ) {
            return false;
          }
          this.toast.hide();
        } else if (this.selectHandle === 2) {
          // 无发现
          const res = await uploadFiles(this.$refs.noFound.uploadImgs); // 上传文件到 OSS
          this.param = {
            assigner: eventId ? this.$route.query.orgLevel : this.userInfo.orgLevel,
            description: this.$refs.noFound.description,
            personEnclosureUrl: JSON.stringify([...res]),
            eventId: this.$route.query.id,
            userId: this.userInfo.userId,
            userName: this.userInfo.userName,
            userOrgId: this.userInfo.groupId,
            userOrgName: this.userInfo.groupName
          };

          if (
            !valiData.call(
              this,
              {
                description: {
                  cond: "String($$).trim().length>0",
                  pro: "请输入情况说明"
                }
              },
              this.param
            )
          ) {
            return false;
          }
          this.toast.hide();
        } else if (this.selectHandle === 4) {
          let user = await this.$refs.illegalPark.getUserInfo()
          this.param = {...this.$refs.illegalPark.submitData, ...user}
          console.log(this.param);
          if (
            !valiData.call(
              this,
              {
                licensePlate: {
                  cond: "String($$).trim().length>6",
                  pro: "请输入正确位数的车牌号"
                },
                plateType: {
                  cond: "String($$).trim().length>0",
                  pro: "请选择号牌种类"
                },
                illegalTime: {
                  cond: "String($$).trim().length>0",
                  pro: "请输入违法时间"
                },
                informBill: {
                  cond: "String($$).trim().length>0",
                  pro: "请输入告知单号"
                },
                agentLesserName: {
                  cond: "String($$).trim().length>0",
                  pro: "请选择承办人"
                },
                road: {
                  cond: "String($$).trim().length>0",
                  pro: "请选择违法道路"
                },
                address: {
                  cond: "String($$).trim().length>0",
                  pro: "请输入详细地址"
                },
                illegal: {
                  cond: "String($$).trim().length>0",
                  pro: "请选择违法行为"
                }
              },
              this.param
            )
          ) {
            return false;
          }
          this.toast.hide();
          return
          
        }
      } catch (err) {
        console.log(err);
        this.toast.hide();
        this.$createToast({
          txt: "图片上传失败",
          type: "error"
        }).show();
        return;
      }

      this.$createDialog({
        type: "confirm",
        icon: "cubeic-alert",
        title: "确认提交？",
        confirmBtn: {
          text: "确定"
        },
        cancelBtn: {
          text: "取消"
        },
        onConfirm: async () => {
          this.toast = this.$createToast({
            time: 0,
            mask: true,
            txt: "提交中...."
          });
          this.toast.show();
          // 上报过程中提交处理需要先上报
          if (this.path == "/event-report") {
            this.$emit("report");
          } else {
            this.finallySubmit();
          }
        }
      }).show();
    },
    //
    async handleSubmit(id) {
      if (!id) {
        this.$createToast({
          txt: "事件上报失败",
          type: "error"
        }).show();
      } else {
        this.param.eventId = id;
        this.finallySubmit();
      }
    },
    async finallySubmit() {
      let code = null;
      if (this.selectHandle === 0) {
        code = await this.handleSubmitAdvised("advised");
      } else if (this.selectHandle === 2) {
        code = await this.handleSubmitNofound();
      } else {
        code = await this.handleSubmitAdvised("correction");
      }
      this.toast.hide();
      if (code === 0) {
        this.$createToast({
          txt: "处理成功",
          type: "correct"
        }).show();
        if (this.path !== "/event-report") {
          setTimeout(() => {
            this.$router.back();
          }, 500);
        } else {
          this.$emit("handleChange", 1);
        }
      } else {
        this.$createToast({
          txt: "处理失败",
          type: "error"
        }).show();
      }
    },
    // 处理 -- 劝改和改正 提交
    async handleSubmitAdvised(type) {
      try {
        let eventNode = this.$route.query.eventNode;
        if (eventNode == "dealCase") {
          this.param.assigner = this.$route.query.orgLevel;
        }
        let res = null;
        if (type == "advised") {
          res = await advised(this.param);
        } else res = await correction(this.param);
        return res.code;
      } catch (err) {
        console.log(err);
        return false;
      }
    },
    // 处理 -- 无发现 提交
    async handleSubmitNofound() {
      try {
        let eventNode = this.$route.query.eventNode;
        if (eventNode == "dealCase") {
          this.param.assigner = this.$route.query.orgLevel;
        }
        let res = await noFoundApi(this.param);
        return res.code;
      } catch (err) {
        console.log(err);
        return false;
      }
    },

    hideMain(bol, type=0) {
      this.btnShow = bol
      if(type) {
        this.barShow = true
      } else this.barShow = false
    }
  }
};
</script>

<style lang="stylus">
@import '../../assets/css/image.styl'
.my-report-handle{
  .handle-content{
    height: calc(100vh - 109px);
    background-color #f6f6f6
    &.fullHeight {
      height 100vh
    }
    .handle-opinion{
      margin-top 10px;
      width: 100%;
      height: 110px;
      background:rgba(255,255,255,1);
      p{
        height: 30px;
        display: flex;
        align-items flex-end;
        font-size:14px;
        font-family:PingFangSC-Regular;
        font-weight:400;
        color:rgba(51,51,51,1);
        text-indent: 10px;
      }
      .cube-textarea-wrapper{
        font-size:14px;
        font-family:PingFangSC-Regular;
        font-weight:400;
        color:rgba(153,153,153,1);
        max-height: 80px;
        .cube-textarea{
          font-size:14px;
          font-family:PingFangSC-Regular;
          font-weight:400;
          color:rgba(153,153,153,1);
          padding-left 15px;
        }
        &::after{
          border: none;
        }
      }
    }
  }
  .bg-white{
    background: #fff;
  }
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }
  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0;
  }
  .cube-input{
    input{
      text-align: right
    }
  }
  .require{
    position: relative
    &:before{
      position: absolute
      left: -12px;
      top: 5px;
      content: '*';
      color: #f00;
    }
  }
  .bind-doc {
    padding 0 0 10px 10px
    .list {
      margin-top 10px
    }
    .cube-input {
      display inline-block
      input {
        text-align left
      }
      &::after {
        border-color #999
      }
    }
    .cube-btn {
      width 80px
      height 40px
      padding 0 12px
      border-radius 2px
      font-size 14px
    }
    .del-btn {
      background-color #f56c6c
      color #fff
      display inline-block
      margin-left 10px
    }
    .add-btn {
      margin-top 10px
    }
  }
  .btn-group{
    position fixed
    bottom 0
    left 0
    z-index 100
    background-color #f5f5f5
    padding 12px 0
    width: 100%;
    height:41px;
    display: flex;
    justify-content: space-around;
    .deal-btn{
      width: 94%;
      height: 41px;
      background:rgba(4,48,102,1);
      border-radius:4px;
      text-align center;
      line-height 41px;
      font-size:15px;
      font-family:PingFangSC-Regular;
      font-weight:400;
      color:rgba(255,255,255,1);
    }
  }
}
.audio-upload .cube-upload-file-def
  border 1px solid #ccc
  background-image url('../../assets/images/audio.png') !important
  background-size 50% 50%
</style>
